package org.apache.http.entity.mime;

import org.apache.http.entity.mime.content.ContentBody;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.descriptor.ContentDescriptor;
import org.apache.james.mime4j.field.Field;
import org.apache.james.mime4j.message.BodyPart;
import org.apache.james.mime4j.message.Header;

public class FormBodyPart extends BodyPart
{
  private final String name;

  public FormBodyPart(String paramString, ContentBody paramContentBody)
  {
    if (paramString == null)
      throw new IllegalArgumentException("Name may not be null");
    if (paramContentBody == null)
      throw new IllegalArgumentException("Body may not be null");
    this.name = paramString;
    setHeader(new Header());
    setBody(paramContentBody);
    generateContentDisp(paramContentBody);
    generateContentType(paramContentBody);
    generateTransferEncoding(paramContentBody);
  }

  private void addField(String paramString)
  {
    try
    {
      getHeader().addField(Field.parse(paramString));
      return;
    }
    catch (MimeException localMimeException)
    {
      throw new UnexpectedMimeException(localMimeException);
    }
  }

  protected void generateContentDisp(ContentBody paramContentBody)
  {
    StringBuilder localStringBuilder = new StringBuilder();
    localStringBuilder.append("Content-Disposition");
    localStringBuilder.append(": form-data; name=\"");
    localStringBuilder.append(getName());
    localStringBuilder.append("\"");
    if (paramContentBody.getFilename() != null)
    {
      localStringBuilder.append("; filename=\"");
      localStringBuilder.append(paramContentBody.getFilename());
      localStringBuilder.append("\"");
    }
    addField(localStringBuilder.toString());
  }

  protected void generateContentType(ContentDescriptor paramContentDescriptor)
  {
    if (paramContentDescriptor.getMimeType() != null)
    {
      StringBuilder localStringBuilder = new StringBuilder();
      localStringBuilder.append("Content-Type");
      localStringBuilder.append(": ");
      localStringBuilder.append(paramContentDescriptor.getMimeType());
      if (paramContentDescriptor.getCharset() != null)
      {
        localStringBuilder.append("; charset=");
        localStringBuilder.append(paramContentDescriptor.getCharset());
      }
      addField(localStringBuilder.toString());
    }
  }

  protected void generateTransferEncoding(ContentDescriptor paramContentDescriptor)
  {
    if (paramContentDescriptor.getTransferEncoding() != null)
    {
      StringBuilder localStringBuilder = new StringBuilder();
      localStringBuilder.append("Content-Transfer-Encoding");
      localStringBuilder.append(": ");
      localStringBuilder.append(paramContentDescriptor.getTransferEncoding());
      addField(localStringBuilder.toString());
    }
  }

  public String getName()
  {
    return this.name;
  }
}